import React from 'react';
import {Popup, PopupTitle} from "@/components/k-view";
import {View, Text} from "@gluestack-ui/themed";
import {CalendarPopupProps} from "./type";
import Calendar from "./Calendar";

const CalendarPopup = (props: CalendarPopupProps) => {
    const {
        isVisible,
        dispatch,
        onSelect,
        onCancel,
        onConfirm,
        title = "选择日期",
        confirmText = "确定",
        cancelText = "取消",
        ...attrs
    } = props;
    const [selectDates, setSelectDates] = React.useState <string[]>([]);
    React.useEffect(() => {
        if (isVisible) setSelectDates([]);
    }, [isVisible])

    // 处理弹窗关闭
    function handleCloseChoosePopup() {
        dispatch({
            type: "close"
        });
    }

    function handleCancel() {
        onCancel && onCancel();
        handleCloseChoosePopup();
    }

    function handleConfirm() {
        onConfirm && onConfirm(selectDates);
        handleCloseChoosePopup();
    }

    function handleSelect(dates: string[]) {
        setSelectDates(dates);
        onSelect && onSelect(dates);
    }

    return (
        <Popup
            isVisible={isVisible}
            mode={"bottom"}
            dispatch={dispatch}
            scrollOffset={0}
            scrollHorizontal={true}
        >
            <View
                bg={"white"}
                borderRadius={"$md"}
            >
                <PopupTitle
                    title={title}
                    renderLeft={<Text color={"$textLight500"}>{cancelText}</Text>}
                    renderRight={<Text color={"$primary500"}>{confirmText}</Text>}
                    onLeftClick={handleCancel}
                    onRightClick={handleConfirm}
                >
                </PopupTitle>
                <Calendar
                    enableSwipeMonths={false}
                    onSelect={handleSelect}
                    {...attrs}
                ></Calendar>
            </View>
        </Popup>
    );
};

export default CalendarPopup;